import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_types.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/models/chat_message/xindong_custom_message.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_score_container.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

class XinDongLiaoTianMessageCallingEnd extends StatelessWidget {
  final V2TimMessage message;
  final XinDongCustomMessage model;

  const XinDongLiaoTianMessageCallingEnd({Key? key, required this.message, required this.model}) : super(key: key);

  Future<void> removeDuplicates(V2TimMessage currentMessage, XinDongCustomMessage messageClass) async {
    String? userID = XinDongChatSingleton.instance.detailClass?.another.uid;
    final chatVM = XinDongChatSingleton.instance.currentChatSeparateVM;
    if (userID == null) return;
    // 原数据，这个数据进行删除操作会抛异常，需要创新临时数据去替换
    List<V2TimMessage> currentHistoryMsgList = chatVM.globalModel.messageListMap[userID] ?? [];
    // 临时数据，可以增删改查
    List<V2TimMessage> tempList = List<V2TimMessage>.from(currentHistoryMsgList);
    // 遍历查询历史消息，进行删除
    for (V2TimMessage message in currentHistoryMsgList) {
      if (message.msgID == currentMessage.msgID) {
        continue;
      }
      XinDongCustomMessage? itemClass = XinDongConversionUtil.decodeJsonToMessageClass(message.customElem?.data ?? "");
      if (messageClass.order_id == itemClass?.order_id && messageClass.order_num == itemClass?.order_num) {
        await TencentImSDKPlugin.v2TIMManager.getMessageManager().deleteMessageFromLocalStorage(msgID: message.msgID!);
        tempList.remove(message);
      }
    }
    chatVM.globalModel.messageListMap[userID] = tempList;
    chatVM.notifyListeners();
  }

  @override
  Widget build(BuildContext context) {
    Future.delayed(Duration.zero).whenComplete(() => removeDuplicates(message, model));
    final isFromSelf = message.isSelf == true;
    final backgroundColor = isFromSelf ? Colors.grey.shade300 : Colors.white;
    final isAudio = int.parse("${model.chat_type}") == ChatType.callAudio;
    String imageName = isAudio ? AssetsRes.CALL_TIME_AUDIO : AssetsRes.CALL_TIME_VIDEO;
    return GetBuilder<XinDongChatSingleton>(
      builder: (controller) {
        return XinDongLiaoTianMessageScoreContainer(
          hidden: false, // 女的强制显示
          message: message,
          score: model.score,
          child: Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(color: backgroundColor, borderRadius: BorderRadius.circular(10)),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageUtil.asset(imageName, width: 20, height: 14, fit: BoxFit.contain),
                Text(
                  " ${model.duration_text}",
                  style: const TextStyle(fontSize: 16, height: 1.2, color: DZColors.titleColor),
                ),
              ],
            ),
            // child: Text.rich(
            //   TextSpan(children: [
            //     WidgetSpan(
            //         child: Container(
            //             width: 20, color: Colors.red, child: ImageHelper.asset(imageName, fit: BoxFit.fitHeight))),
            //     TextSpan(text: " ${model.duration_text}"),
            //   ]),
            //   // textAlign: TextAlign.left,
            //   // softWrap: true,
            //   style: const TextStyle(fontSize: 16, height: 1.2, color: DZColors.titleColor),
            // ),
          ),
        );
      },
    );
  }
}
